$(function() {
	$('.fancybox').fancybox();
});

function userSave() {
	console.log("save clicked");
	continueTest = true;
	pattern = new RegExp("^[A-z0-9-]+$");
	//Get the username
	un = $('#username-input').attr('value');
	console.log("username received: ", un);
	console.log("testing regex: ", pattern.test(un));
	if (pattern.test(un) == false) {
		console.log("failed");
		un = null;
		continueTest = false;
		console.log("set continue to false");
		$('#unError').text("Invalid characters. Only letters, numbers, and hypens are allowed");
	} else if (un.length > 30) {
		console.log("failed");
		un = null;
		continueTest = false;
		console.log("set continue to false");
		$('#unError').text("Your user name is too long. Please limit your user name to 30 characters");
	}
	
	//Get the selected radio button
	rb = $("input[name*=radio-choice]:checked").val();
	console.log("radio button received: ", rb);
	
	if (continueTest == true || rb != null) {
		console.log("valid input");
		unSend = "";
		if (continueTest == true) {
			console.log("setting un");
			unSend = un;
		} else {
			console.log("setting rb");
			unSend = rb;
		}
		console.log("unSend: ", unSend);
		//Submit the username for server validation
		dataString = "code=1&usern=" + unSend;
		$.ajax({
			type: "POST",
			url: "/tuser",
			data: dataString,
			success: function(data) {
				console.log("ajax success: ", data);
				if (data.status == "ok") {
					//Name has been saved successfully
					$('#currentUn').text(unSend);
					showSuccess();
				} else if (data.status == "in_use") {
					$('#unError').text("Name in use. Type another or select from below and press save");
					suggest = data.suggestions;
					
					//clear input field
					$('#username-input').attr('value', '');
					
					//Loop through the suggestions and apply to form
					suggHtml = "";
					for (n in suggest) {
						//Set the radio text and value
						suggHtml += '<input type="radio" name="radio-choice" value="' + suggest[n] + '">' + suggest[n] + '<br>';
					}
					$('#unSuggestions').html(suggHtml);
					$.fancybox.update()
				}
			},
			error: function() {
				$('#unError').text("Network error - please try again later");
			}
		});
	} else if (continueTest == true) {
		$('#unError').text("No username entered (your current username is above)");
	}
}

function showSuccess() {
	$('#username-input').attr('value', '');
	$('#unSuggestions').html("");
	$('#unError').text("");
	$.fancybox.close( '#username-update-dialog' );
	$.fancybox.open( '#username-success' );
}